import eveapi
import os
import logging
import zlib
import time
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

_DEBUG = True

def startApi():
	cacheHandler = EveApiCacheHandler()
	api = eveapi.EVEAPIConnection(cacheHandler=cacheHandler)
	return api

class EveApiCacheHandler(object):
	LENGTH_THRESHOLD = 500000 # Bytes
	EXPECTED_ZLIB_HEADER = u"x\x9c"
	
	def _createKey(self, host, path, params):
		cacheKey = str(host) + str(path)
		first = True
		sep = '?'
		for key, value in params.items():
			cacheKey += sep + str(key) + '=' + str(value)
			if first == True:
				first = False
				sep = '&'
		return cacheKey

	def retrieve(self, host, path, params):
		cacheKey = self._createKey(host, path, params)
		#logging.info(cacheKey)
		
		data = memcache.get(cacheKey)
		
		if data is None:
			return None
		if data.startswith(self.EXPECTED_ZLIB_HEADER):
			data = zlib.decompress(data.encode('ISO-8859-1'))
		return data
	
	def store(self, host, path, params, doc, obj):
		cacheKey = self._createKey(host, path, params)
		
		data = doc
		if len(data) > self.LENGTH_THRESHOLD and not data.startswith(self.EXPECTED_ZLIB_HEADER):
			data = unicode(zlib.compress(data), 'ISO-8859-1')
			
		logging.debug(str(time.time()) + ' - Now')
		logging.debug(str(int(obj.cachedUntil)) + ' - Cache Until')
		memcache.set(cacheKey, data, time=obj.cachedUntil)
	
class BaseRequestHandler(webapp.RequestHandler):
	"""Supplies a common template generation function.

	When you call generate(), we augment the template variables supplied with
	the current user in the 'user' variable and the current webapp request
	in the 'request' variable.
	"""
	def generate(self, template_name, template_values={}):
		values = {
			'request': self.request,
			'application_name': 'EVE POS Tracker'
			}
		values.update(template_values)
		directory = os.path.dirname(__file__)
		path = os.path.join(directory, os.path.join('templates', template_name))
		self.response.out.write(template.render(path, values, debug=_DEBUG))

